#include "ByteArrayOutputStream.h"
#include "lang/Exception.h"
#include "lang/String.h"
#include "array/Arrays.h"
using namespace yzrilyzr_lang;
using namespace yzrilyzr_array;
namespace yzrilyzr_io{
	void ByteArrayOutputStream::ensureCapacity(u_index minCapacity){
		u_index oldCapacity=buf.length;
		u_index minGrowth=minCapacity - oldCapacity;
		if(minGrowth > 0){
			buf=Arrays::copyOf(buf, Arrays::newLength(oldCapacity,minGrowth,oldCapacity));
		}
	}

	ByteArrayOutputStream::ByteArrayOutputStream() :ByteArrayOutputStream(32){}
	ByteArrayOutputStream::ByteArrayOutputStream(u_index size){
		if(size < 0){
			throw Exception("Negative initial size: " + std::to_string(size));
		}
		buf=ByteArray(size);
	}
	ByteArrayOutputStream::~ByteArrayOutputStream(){
		
	}
	void ByteArrayOutputStream::write(int32_t b){
		ensureCapacity(count + 1);
		buf[count]=(int8_t)b;
		count+=1;
	}
	void ByteArrayOutputStream::write(const ByteArray & b, u_index off, u_index len){
		ensureCapacity(count + len);
		System::arraycopy(b, off, buf, count, len);
		count+=len;
	}
	void ByteArrayOutputStream::writeBytes(const ByteArray & b){
		write(b, 0, b.length);
	}
	void ByteArrayOutputStream::writeTo(OutputStream & out){
		out.write(buf, 0, count);
	}
	void ByteArrayOutputStream::reset(){
		count=0;
	}
	ByteArray ByteArrayOutputStream::toByteArray()const{
		return Arrays::copyOf(buf,count);
	}
	u_index ByteArrayOutputStream::size()const{
		return count;
	}
	String ByteArrayOutputStream::toString()const{
		return String(buf, 0, count);
	}
	String ByteArrayOutputStream::toString(StringEncoding encoding)const{
		return String(buf, 0, count, encoding);
	}
	void ByteArrayOutputStream::close(){}
}